package com.itheima.service.mongo.impl;


import cn.hutool.core.bean.BeanUtil;
import com.itheima.domain.mongo.Report;
import com.itheima.service.mongo.ReportService;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@DubboService
public class ReportServiceImpl implements ReportService {

    @Autowired
    private MongoTemplate mongoTemplate;


    //保存问卷
    @Override
    public String save(Report report) {
        //判断是否存在同级别的报告
        Query query = new Query(Criteria.where("userId").is(report.getUserId()).and("testSoulId").is(report.getTestSoulId()));
        Report report1 = mongoTemplate.findOne(query, Report.class);
        ObjectId id =null;
        if (report1==null) {//报告不存在
            mongoTemplate.save(report,"test_soul_report");
            id=report.getId();
        }else {//存在，更新
            id=report1.getId();
            BeanUtil.copyProperties(report,report1);
            report1.setId(id);
            mongoTemplate.save(report1);
        }
        return id.toHexString();
    }
    //查询相似
    @Override
    public List<Report> findSim(Integer conclusionId, String testSoulId) {
        Query query = new Query(Criteria.where("conclusionId").is(conclusionId).and("testSoulId").is(testSoulId));
        return mongoTemplate.find(query, Report.class);
    }
    //查看问卷
    @Override
    public Report findById(String id) {
        return mongoTemplate.findById(new ObjectId(id), Report.class);
    }
    //查看问卷记录,存在则返回最新报告id
    @Override
    public String findNearReport(Long userId) {
        //构造条件
        Query query = new Query(Criteria.where("userId").is(userId)).with(Sort.by(Sort.Order.desc("created"))).skip(0).limit(1);
        //查询
        Report report = mongoTemplate.findOne(query, Report.class);
        //判断
        if (report==null) {
            return null;
        }else {
            return report.getId().toHexString();
        }
    }
}
